import React, { Fragment}from 'react';
import { Layout, Icon, Menu, Tabs, Row,Col } from 'antd';
import DocumentTitle from 'react-document-title';
import isEqual from 'lodash/isEqual';
import memoizeOne from 'memoize-one';
import { connect } from 'dva';
import { ContainerQuery } from 'react-container-query';
import classNames from 'classnames';
import pathToRegexp from 'path-to-regexp';
import { enquireScreen, unenquireScreen } from 'enquire-js';
import SiderMenu from '@/components/SiderMenu';
import Authorized from '@/utils/Authorized';
import logo from '../assets/header.png';
// import Footer from './Footer';
import Header from './Header';
import Context from './MenuContext';
import router from 'umi/router';

// 
// import rxr from "@/components/Panes"
// 

// Conversion router to menu.
function formatter(data, parentAuthority, parentName) {
  return data
    .map(item => {
      let locale = 'menu';
      if (parentName && item.name) {
        locale = `${parentName}.${item.name}`;
      } else if (item.name) {
        locale = `menu.${item.name}`;
      } else if (parentName) {
        locale = parentName;
      }
      if (item.path) {
        const result = {
          ...item,
          // locale,
          authority: item.authority || parentAuthority,
        };
        if (item.routes) {
          const children = formatter(item.routes, item.authority, locale);
          // Reduce memory usage
          result.children = children;
        }
        delete result.routes;
        return result;
      }

      return null;
    })
    .filter(item => item);
}

const memoizeOneFormatter = memoizeOne(formatter, isEqual);

const query = {
  'screen-xs': {
    maxWidth: 575,
  },
  'screen-sm': {
    minWidth: 576,
    maxWidth: 767,
  },
  'screen-md': {
    minWidth: 768,
    maxWidth: 991,
  },
  'screen-lg': {
    minWidth: 992,
    maxWidth: 1199,
  },
  'screen-xl': {
    minWidth: 1200,
    maxWidth: 1599,
  },
  'screen-xxl': {
    minWidth: 1600,
  },
};

class BasicLayout extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      rendering: true,
      isMobile: false,
      menuData: {}, //this.getMenuData()
      activeKey: "1",
      panes:[],
      showPane:""
    };

    this.getPageTitle = memoizeOne(this.getPageTitle);
    this.getBreadcrumbNameMap = memoizeOne(this.getBreadcrumbNameMap, isEqual);
    this.breadcrumbNameMap = this.getBreadcrumbNameMap();
    this.matchParamsPath = memoizeOne(this.matchParamsPath, isEqual);
  }
  componentDidMount() {
    const { dispatch,children } = this.props;
    const _this = this;
    // dispatch({
    //   type: 'menuTree/getMenu',
    // });
    dispatch({
      type: 'menuTree/getAllMenu',
      callback:(res)=>{
        if(res.code === "000000" && res.menus.length > 0){
          const data = {
            dom: children,
            path: res.menus[0].path
          }
          _this.setState((prevState) => {
            return { 
              showPane: res.menus[0].routes[0].path
            };
          });
        }
      }
    });
    this.renderRef = requestAnimationFrame(() => {
      this.setState({
        rendering: false,
      });
    });
    this.enquireHandler = enquireScreen(mobile => {
      const { isMobile } = this.state;
      if (isMobile !== mobile) {
        this.setState({
          isMobile: mobile,
        });
      }
    });
    //
  }
  componentDidUpdate(preProps) {
    // After changing to phone mode,
    // if collapsed is true, you need to click twice to display
    this.breadcrumbNameMap = this.getBreadcrumbNameMap();
    const { isMobile } = this.state;
    const { collapsed } = this.props;
    if (isMobile && !preProps.isMobile && !collapsed) {
      this.handleMenuCollapse(false);
    }
  }
  componentWillReceiveProps(nextProps){
    console.log("BasicLayout", nextProps,this.props)
    const { children, dispatch } = nextProps
    const { panes } = this.state;
/**
 * 待优化
 * 期望可以Url不跳转
 * 期望可以重复点击时不去请求--setPanel
 */
    if (nextProps.location.search.indexOf("sort") !== -1){
      if (nextProps.location.pathname !== this.props.location.pathname){
        console.log("请求：---setPanel")
        dispatch({
          type: 'menuTree/setPanel',
          payload: children
        });    
        const backurl = nextProps.location.query.sort || false
        backurl && router.replace(backurl)
      }

      return 
    }
// 
    let flag = true;
    panes.filter(item => item.path !== "/").map(item => {
      if (item.path === nextProps.location.pathname) {
        this.setState(() => {
          return { showPane: nextProps.location.pathname }//显示prop.path
        })
        flag = false
        return
      }
    })
    if (flag) {
      const data = {
        path: nextProps.location.pathname,
        dom: children
      }
      this.setState((prevState) => {
        return {
          panes: prevState.panes.concat(data),
          showPane: data.path
        };
      });
    }
  }
  componentWillUnmount() {
    cancelAnimationFrame(this.renderRef);
    unenquireScreen(this.enquireHandler);
  }

  getContext() {
    const {
      location,
      menuTree: { menuData },
    } = this.props;
    const routerMap = {};
    const mergeMenuAndRouter = data => {
      data.forEach(menuItem => {
        if (menuItem.children) {
          mergeMenuAndRouter(menuItem.children);
        }
        // Reduce memory usage
        routerMap[menuItem.path] = menuItem;
      });
    };
    mergeMenuAndRouter(formatter(menuData));
    if (routerMap && Object.keys(routerMap).length) {
      return {
        location,
        breadcrumbNameMap: routerMap,
      };
    }
  }

  getMenuData() {
    const {
      route: { routes },
    } = this.props;
    return memoizeOneFormatter(routes);
  }

  /**
   * 获取面包屑映射
   * @param {Object} menuData 菜单配置
   */
  getBreadcrumbNameMap() {
    const routerMap = {};
    const mergeMenuAndRouter = data => {
      data.forEach(menuItem => {
        if (menuItem.children) {
          mergeMenuAndRouter(menuItem.children);
        }
        // Reduce memory usage
        routerMap[menuItem.path] = menuItem;
      });
    };
    const { menuTree } = this.props;
    const { menuData } = menuTree;
    mergeMenuAndRouter(formatter(menuData));
    return routerMap;
  }

  matchParamsPath = pathname => {
    const pathKey = Object.keys(this.breadcrumbNameMap).find(key =>
      pathToRegexp(key).test(pathname)
    );
    return this.breadcrumbNameMap[pathKey];
  };

  getPageTitle = pathname => {
    const currRouterData = this.matchParamsPathDIY(pathname);
    if (!currRouterData) {
      return '盾泰云平台';
    }
    return `${currRouterData.name}`;
  };
  // 权限自定义--start
  matchParamsPathDIY = pathname => {
    const routerMap = {};
    const mergeMenuAndRouter = data => {
      data.forEach(menuItem => {
        if (menuItem.children) {
          mergeMenuAndRouter(menuItem.children);
        }
        routerMap[menuItem.path] = menuItem;
      });
    };
    const { menuTree } = this.props;
    const { menuData } = menuTree;
    mergeMenuAndRouter(formatter(menuData));

    if (routerMap && Object.keys(routerMap).length) {
      const pathKey = Object.keys(routerMap).find(key => pathToRegexp(key).test(pathname));

      if (pathKey == undefined && pathname !== '/') {
        return 'other';
      } else {
        return routerMap[pathKey];
      }
    }
  };
  // end

  getLayoutStyle = () => {
    const { isMobile } = this.state;
    const { fixSiderbar, collapsed, layout } = this.props;
    if (fixSiderbar && layout !== 'topmenu' && !isMobile) {
      return {
        paddingLeft: collapsed ? '80px' : '256px',
      };
    }
    return null;
  };

  getContentStyle = () => {
    const { fixedHeader } = this.props;
    return {
      margin: '24px 24px 0',
      paddingTop: fixedHeader ? 64 : 0,
    };
  };
  antBar=()=>{
    return {
      position: "fixed",
      zIndex:10,
      right:0,
      left:0,
      height:"64px",
      paddingRight: "10px",
      paddingLeft: "10px",
      borderBottom:"0px",
      backgroundColor: "#001529"
    };
  }
  antFooter=()=>{
    return {
      position: "fixed",
      zIndex:10,
      bottom:0,
      right:0,
      left:0,
      textAlign:"center",
      padding:"5px",
      height:"30px",
      paddingRight: "10px",
      paddingLeft: "10px",
      borderBottom:"0px",
      backgroundColor: "#F0F2F5"
    };
  }
  antNav=()=>{
    return {
      height:"100%",
      paddingBottom: "20px",
      paddingTop: "64px"
    };
  }
  antLogo=()=>{
    return {
      width: "120px",
      height: "31px",
      background: "rgba(255, 255, 255, .2)",
      margin: "16px 24px 16px 0",
      float: "left",
    };
  }
  paneShow=()=>{
    return{
      display:"block"
    }
  }
  paneHiden=()=>{
    return{
      display:"none"
    }
  }
  handleMenuCollapse = collapsed => {
    //折叠菜单
    const { dispatch } = this.props;
    dispatch({
      type: 'global/changeLayoutCollapsed',
      payload: collapsed,
    });
  };
  onChange = (activeKey) => {
    this.setState({ activeKey });
  }
  onEdit = (targetKey, action) => {
    this[action](targetKey);
  }
  remove = (targetKey) => {
    let activeKey = this.state.activeKey;
    let lastIndex;
    this.state.panes.forEach((pane, i) => {
      if (pane.key === targetKey) {
        lastIndex = i - 1;
      }
    });
    const panes = this.state.panes.filter(pane => pane.key !== targetKey);
    if (lastIndex >= 0 && activeKey === targetKey) {
      activeKey = panes[lastIndex].key;
    }
    this.setState({ panes, activeKey });
  }
  menuClick=(prop,index)=>{
    // console.log("menuClick", e)
    const {panes} = this.state;
    let flag = true;
    panes.map(item =>{
      if (item.path === prop.children[0].path){
        this.setState(()=>{
          return { showPane: prop.children[0].path }//显示prop.path
        })
        flag = false
        return
      }
    })
    if (flag) {
      const path = prop.children[0].path;
      router.push(path)
    }
  }
  render() {
    const {
      layout: PropsLayout,
      location: { pathname },
      navTheme,
      children,
      menuTree: { menuData },
    } = this.props;
    const {panes,showPane,isMobile} = this.state;
    const isTop = PropsLayout === 'topmenu';
    const menuList = formatter(menuData);
    const routerConfig = this.matchParamsPathDIY(pathname);
    // console.log("panes", panes, showPane)
    const layout = (
      // <Layout
      //   style={{
      //     ...this.getLayoutStyle(),
      //     minHeight: '100vh',
      //   }}
      // >
        // <Header
        //   menuData={menuList}
        //   handleMenuCollapse={this.handleMenuCollapse}
        //   logo={logo}
        //   isMobile={isMobile}
        //   {...this.props}
        // />
        // <Layout>
        //   <Sider>Sider</Sider>
          // <Content style={this.getContentStyle()}>
          //   {routerConfig == 'other' ? (
          //     <Exception403 />
          //   ) : (
          //       <Authorized
          //         authority={routerConfig && routerConfig.authority}
          //         noMatch={<Exception403 />}
          //       >
          //         {children}
          //       </Authorized>
          //     )}
          // </Content>
        // </Layout>
      //   <Footer />
      // </Layout>
      <Layout
          style={{
            ...this.getLayoutStyle(),
            minHeight: '100vh',
          }}
        >
      <Fragment>
          {isTop && !isMobile ? null : (
            <SiderMenu
              logo={logo}
              Authorized={Authorized}
              theme={navTheme}
              onCollapse={this.handleMenuCollapse}
              menuData={menuList}
              isMobile={isMobile}
              {...this.props}
            />
          )}
          <header className="ant-bar">
            <Header
              menuData={menuList}
              handleMenuCollapse={this.handleMenuCollapse}
              logo={logo}
              isMobile={isMobile}
              menuClick={this.menuClick}
              {...this.props}
            />
          </header>
          <nav className="ant-nav" style={this.antNav()}>
            {/* <Layout>
              <Content>
                {routerConfig == 'other' ? (
                  <Exception403 />
                ) : (
                    <Authorized
                      authority={routerConfig && routerConfig.authority}
                      noMatch={<Exception403 />}
                    >
                      {children}
                    </Authorized>
                  )}
              </Content>
            </Layout> */}
            {panes && Object.keys(panes).length ?  
              <Fragment>
                {panes.map((item, index) => {
                  return(
                    <Fragment key={index}>
                      <section data-id={item.path} style={item.path == showPane ? this.paneShow() : this.paneHiden()}>
                        {item.dom}
                      </section>
                    </Fragment>
                  )
                })} 
              </Fragment>
              :null}
          </nav>
          <div className="ant-bar ant-footer" style={this.antFooter()}>
            <Fragment>
              Copyright <Icon type="copyright" /> 2018 江苏盾泰体验技术部出品
            </Fragment>
          </div>
      </Fragment>
      </Layout>
    );
    return (
      <React.Fragment>
        <DocumentTitle title={this.getPageTitle(pathname)}>
          <ContainerQuery query={query}>
            {params => (
              <Context.Provider value={this.getContext()}>
                {menuList && Object.keys(menuList).length ? (
                  <div className={classNames(params)}>{layout}</div>
                ) : null}
              </Context.Provider>
            )}
          </ContainerQuery>
        </DocumentTitle>
        {/* {menuList && Object.keys(menuList).length ? (
          <Fragment>{layout}</Fragment>
        ) : null} */}
      </React.Fragment>
    );
  }
}

export default connect(({ menuTree, global, setting }) => ({
  menuTree,
  collapsed: global.collapsed,
  layout: setting.layout,
  ...setting,
}))(BasicLayout);
